package com.leave.controller;

import java.util.HashMap;
import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.leave.entity.Leave;
import com.leave.entity.User;
import com.leave.service.ILeaveService;
import com.leave.service.IUserService;
import com.leave.util.DateUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class TaskController {
	@Autowired
	private TaskService taskService;
	@Autowired
	private IUserService userService;
	@Autowired
	private ILeaveService leaveService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private IdentityService identityService;
	
	/**
	 * 分页查询当前用户的待办任务列表
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("/getDaiBanTaskByPage")
	@ResponseBody
	public String getDaiBanTaskByPage(Integer page,Integer rows) {
	
		Subject currentUser = SecurityUtils.getSubject();  
		User user = (User) currentUser.getPrincipal();
		//获取待办任务数量
		Long total = taskService.createTaskQuery().taskCandidateUser(user.getUserId()+"").count();
		//获取待办任务的列表
		List<Task> taskList = taskService.createTaskQuery().taskCandidateUser(user.getUserId()+"").listPage((page-1)*rows, rows);
		
		JSONArray jsArr = new JSONArray();
		for(Task task : taskList) {
			JSONObject js = new JSONObject();
			js.put("taskId", task.getId());
			js.put("taskName", task.getName());
			js.put("createTime", DateUtil.formatDate(task.getCreateTime(), "yyyy-MM-dd HH:mm"));
			jsArr.add(js);
		}
		JSONObject js = new JSONObject();
		js.put("rows", jsArr);
		js.put("total", total);
		return js.toString();
	}
	
	/**
	 * 审批任务
	 * @param flg
	 * @param taskId 
	 * @param comment 批注
	 * @return
	 */
	@RequestMapping("/approveTask")
	@ResponseBody
	public String approveTask(String flg,String taskId,String comment) {
		
		HashMap<String,Object> processVar = (HashMap<String, Object>) taskService.getVariables(taskId);
		Task task =  taskService.createTaskQuery().taskId(taskId).singleResult();
		//添加批注
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		String roleName = (String) session.getAttribute("roleName");
		User user = (User) currentUser.getPrincipal();
		identityService.setAuthenticatedUserId(user.getUserNickname()+"["+roleName+"]");
		taskService.addComment(taskId, task.getProcessInstanceId(), comment); 
		switch (roleName) {
		case "项目组长":
			if("ok".equals(flg)) {
				String zjIds = getUserIdsByRoleName("项目总监");
				String jlIds = getUserIdsByRoleName("项目经理");
				processVar.put("zongjian", zjIds);
				processVar.put("jingli", jlIds);
				processVar.put("isPass", "true");
			}else {
				processVar.put("isPass", "false");
				int id = (Integer) processVar.get("leaveId");
				Leave leave = leaveService.getLeaveByLeaveId(id);
				leave.setLeaveState("审核未通过");
				leaveService.updateLeaveByLeave(leave);
			}
			taskService.complete(taskId,processVar);
			break;
		case "项目经理":
		case "项目总监":
			String hrIds = getUserIdsByRoleName("人事部经理");
			processVar.put("hr", hrIds);
			taskService.complete(taskId,processVar);
			break;
		case "人事部经理":
			int id = (Integer) processVar.get("leaveId");
			Leave leave = leaveService.getLeaveByLeaveId(id);
			int leaveDay = leave.getLeaveDay();
			if(leaveDay > 7) {
				String zongcaiIds = getUserIdsByRoleName("公司总裁");
				processVar.put("zongcai", zongcaiIds);
			}else {
				String fuzongcaiIds = getUserIdsByRoleName("公司副总裁");
				processVar.put("fuzongcai", fuzongcaiIds);
			}
			processVar.put("leaveDay",leaveDay);
			taskService.complete(taskId,processVar);
			break;
		case "公司总裁":
		case "公司副总裁":
			taskService.complete(taskId,processVar);
			break;
		}
		return "success";
	}
	
	/**
	 * 查看已办任务管理
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("/getYiBanTaskByPage")
	@ResponseBody
	public String getYiBanTaskByPage(Integer page,Integer rows) {
		Subject currentUser = SecurityUtils.getSubject();  
		User user = (User) currentUser.getPrincipal();
		Long total = historyService.createHistoricTaskInstanceQuery()
						.taskCandidateUser(user.getUserId()+"").count();
		List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery().finished()
				.taskCandidateUser(user.getUserId()+"").listPage((page-1)*rows, rows);
		
		JSONArray jsArr = new JSONArray();
		for(HistoricTaskInstance task : taskList) {
			JSONObject js = new JSONObject();
			js.put("taskId", task.getId());
			js.put("taskName", task.getName());
			js.put("createTime", DateUtil.formatDate(task.getCreateTime(), "yyyy-MM-dd HH:mm"));
			js.put("overTime", DateUtil.formatDate(task.getEndTime(), "yyyy-MM-dd HH:mm"));
			jsArr.add(js);
		}
		JSONObject js = new JSONObject();
		js.put("rows", jsArr);
		js.put("total", total);
		return js.toString();
	}
	
	/**
	 * 查看流程执行过程
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/viewProcess")
	@ResponseBody
	public String viewProcess(String taskId) {
		//根据任务id,获取历史任务实例
		HistoricTaskInstance hidTask = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
		//获取流程实例id
		String processInstanceId=hidTask.getProcessInstanceId();
		//根据流程实例id获取流程活动历史节点
		List<HistoricTaskInstance> hidTaskList = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();
		
		JSONArray jsArr = new JSONArray();
		for(HistoricTaskInstance task : hidTaskList) {
			JSONObject js = new JSONObject();
			js.put("taskPointId", task.getId());
			js.put("taskPointName", task.getName());
			js.put("createTime", DateUtil.formatDate(task.getCreateTime(), "yyyy-MM-dd HH:mm"));
			js.put("endTime", DateUtil.formatDate(task.getEndTime(), "yyyy-MM-dd HH:mm"));
			jsArr.add(js);
		}
		JSONObject js = new JSONObject();
		js.put("rows", jsArr);
		return js.toString();
	}
	
	/**
	 * 查看历史批注
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/viewHistory")
	@ResponseBody
	public String viewHistory(String taskId) {
		//根据任务id,获取历史任务实例
		HistoricTaskInstance hidTask = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
		List<Comment> commentList = taskService.getProcessInstanceComments(hidTask.getProcessInstanceId());
		JSONArray jsArr = new JSONArray();
		for(Comment comment : commentList) {
			JSONObject js = new JSONObject();
			js.put("reviewTime", DateUtil.formatDate(comment.getTime(), "yyyy-MM-dd HH:mm"));
			js.put("reviewPerson", comment.getUserId());
			js.put("reviewContent", comment.getFullMessage());
			jsArr.add(js);
		}
		JSONObject js = new JSONObject();
		js.put("rows", jsArr);
		return js.toString();
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 根据角色名称获取对应的所有用户id的字符串，用逗号连接
	 * @param roleName
	 * @return
	 */
	public String getUserIdsByRoleName(String roleName) {
		List<User> userList = userService.getUserListByRole(roleName);
		String userIds = "";
		for(int i = 0;i < userList.size();i++) {
			userIds += userList.get(i).getUserId();
			if(i != userList.size()-1) {
				userIds += ',';
			}
		}
		return userIds;
	}
	
	
	
	
	
	
	
}
